package com.qd.system.service.msg.log;

import com.cdqidi.exception.QueueIsEmptyException;
import com.qd.system.model.MsgReceiveContent;
import com.qd.system.service.msg.base.MsgReceiveContentService;
import com.qd.system.service.msg.server.MsgProcess;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ProcessReceiveContentLog extends Thread {

    private boolean done;
    private final MsgReceiveContentService msgReceiveContentService;

    public ProcessReceiveContentLog(int idx, MsgReceiveContentService msgReceiveContentService) {
        super("消息上行内容日志" + idx);
        this.msgReceiveContentService = msgReceiveContentService;
    }

    @Override
    public void run() {
        log.info(this.getName() + "处理线程已启动!");
        List<MsgReceiveContent> dataList = new ArrayList<>(500);
        long c = 0;
        long st;
        long et = 0;
        List<MsgReceiveContent> retryDataList = null;
        while (!done) {
            try {
                if (dataList.isEmpty()) {
                    MsgProcess.getInstance().getReceiveContentLogSize(dataList);
                }
                if (retryDataList != null) {
                    msgReceiveContentService.saveBatch(retryDataList);
                    c += retryDataList.size();
                    retryDataList.clear();
                }
                while (!done) {
                    if (!dataList.isEmpty()) {
                        try {
                            st = System.currentTimeMillis();
                            msgReceiveContentService.saveBatch(dataList);
                            c += dataList.size();
                            dataList.clear();
                            et += (System.currentTimeMillis() - st);
                        } finally {
                            if (!dataList.isEmpty()) {
                                retryDataList = dataList;
                            }
                        }
                        if ((c % 2000) == 0) {
                            log.info(this.getName() + "  总计：" + c + "/" + MsgProcess.getInstance().getReceiveContentLogSize() + "条     速度：" + (et / 2000) + "毫秒     耗时：" + et + "毫秒/2000条");
                            et = 0;
                        }
                    }
                    buildDataList(dataList);
                }
            } catch (QueueIsEmptyException ignored) {
            } catch (Throwable e) {
                log.error("e", e);
            }
        }
    }

    private static void buildDataList(List<MsgReceiveContent> dataList) {
        try {
            MsgProcess.getInstance().getReceiveContentLogSize(dataList);
        } catch (QueueIsEmptyException ignored) {
        }
    }

    public void doDone() {
        done = true;
    }
}
